package frpc.application.web;

import fdupc.http.ResultBean;
import frpc.application.CacheDescribe;
import frpc.boot.manager.ICacheDescriptionManager;
import frpc.enu.CacheDescriptionType;
import frpc.manager.SimpleRedisBaskManager;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * 类描述:  Redis管理交互
 *
 * @author 王雷
 * @version 1.0.0
 * @date 2022/6/22 0022 下午 3:39
 */
@Slf4j
public class RedisManagerController extends SimpleRedisBaskManager implements IRedisManagerController {

    /**
     * 功能描述：获取所有缓存描述
     *
     * @date : 2022/6/22 0022 下午 3:41
     */
    @Override
    @ResponseBody
    public ResultBean giveRedisCacheList(@RequestParam(required = false) String redisKey) {
        if (!StringUtils.isNotEmpty(redisKey)) {
            return giveRedisAllToList();
        }
        return giveRedisByKey(redisKey);
    }

    /**
     * 功能描述：清空Redis缓存描述
     *
     * @date : 2022/6/22 0022 下午 3:41
     */
    @Override
    @ResponseBody
    public ResultBean clearRedisCacheDescription() {
        try {
            giveSpringBean(ICacheDescriptionManager.class).clearCacheDescription();
            return ResultBean.factorySuccess();
        } catch (Exception e) {
            log.error("初始化缓存描述异常", e);
            return ResultBean.factoryError();
        }
    }

    /**
     * 功能描述：获取所有缓存描述
     *
     * @date : 2022/6/22 0022 下午 3:41
     */
    @Override
    @ResponseBody
    public ResultBean giveRedisByKey(@RequestParam(required = false) String key) {
        try {
            if (!StringUtils.isNotEmpty(key)) {
                return ResultBean.factorySuccess();
            }
            final List<CacheDescribe> cacheDescribeList = new CopyOnWriteArrayList<>();
            final ICacheDescriptionManager iCacheDescriptionManager = giveSpringBean(ICacheDescriptionManager.class);
            giveRedisBasicsBusinessManager().readKeys(key).parallelStream().forEach(readKey->{
                try {
                    final CacheDescribe build = CacheDescribe.builder().cacheKey(readKey).isExistData(Boolean.TRUE)
                            .isExistConfig(Boolean.FALSE).cacheMessage(iCacheDescriptionManager.keyComparison(key))
                            .cacheDescriptionType(CacheDescriptionType
                                    .giveCacheDescriptionTypeByDataType(giveRedisBasicsBusinessManager()
                                            .giveTypeToKey(readKey))).build();
                    if (iCacheDescriptionManager.doesItExist(key)) {
                        build.setIsExistConfig(Boolean.TRUE);
                    }
                    cacheDescribeList.add(build);
                }catch(Exception e){
                    log.error("处理：{}；处理异常；", key, e);
                }
            });
            return ResultBean.factorySuccess(cacheDescribeList);
        } catch (Exception e) {
            log.error("执行异常", e);
            return ResultBean.factoryError();
        }
    }

    /**
     * 功能描述：获取所有缓存描述
     *
     * @date : 2022/6/22 0022 下午 3:41
     */
    @Override
    @ResponseBody
    public ResultBean giveRedisAllToList() {
        try {
            final ICacheDescriptionManager iCacheDescriptionManager = giveSpringBean(ICacheDescriptionManager.class);
            final List<CacheDescribe> cacheDescribeList = new CopyOnWriteArrayList<>();

            final Set<String> cacheKeySet = iCacheDescriptionManager.giveCacheKeyToSet();
            cacheKeySet.parallelStream().forEach(cacheKey -> {
                try {
                    final Set<String> redisKeySet = giveRedisBasicsBusinessManager().readKeys(cacheKey);
                    redisKeySet.parallelStream().forEach(redisKey -> {
                        try {
                            String keyComparison = iCacheDescriptionManager.keyComparison(cacheKey);
                            cacheDescribeList.add(CacheDescribe.builder().cacheKey(redisKey).isExistData(Boolean.TRUE)
                                    .isExistConfig(Boolean.TRUE).cacheMessage(keyComparison)
                                    .cacheDescriptionType(CacheDescriptionType
                                            .giveCacheDescriptionTypeByDataType(giveRedisBasicsBusinessManager().giveTypeToKey(redisKey)))
                                    .build());
                        } catch (Exception e) {
                            log.error("通过：{}；获取keyComparison出现异常", cacheKey, e);
                        }

                    });
                }catch(Exception e){
                    log.error("获取所有缓存描述处理异常", e);
                }
            });
            return ResultBean.factorySuccess(cacheDescribeList);
        } catch (Exception e) {
            log.error("执行异常", e);
            return ResultBean.factoryError();
        }
    }

    /**
     * 属性描述：根据Key清除缓存
     *
     * @date : 2022/6/22 0022 下午 5:32
     */
    @Override
    @ResponseBody
    public ResultBean delRedisCacheByKey(@RequestBody String keys) {
        if (keys != null) {
            try {
                giveRedisBasicsBusinessManager().del(keys.split(","));
            }catch(Exception e){
                log.error("根据Key清除缓存处理异常", e);
                return ResultBean.factoryError();
            }
        }
        return ResultBean.factorySuccess();
    }

    /**
     * 属性描述：根据Key获取缓存存储的数据
     *
     * @date : 2022/6/22 0022 下午 5:32
     */
    @Override
    @ResponseBody
    public ResultBean giveRedisCacheByKey(@RequestParam String key) {
        if (!StringUtils.isNotEmpty(key)) {
            try {
                switch (giveRedisBasicsBusinessManager().giveTypeToKey(key)) {
                    case STRING:
                        return ResultBean.factorySuccess(giveRedisSerializableManager().giveValueByKey(key));
                    case LIST:
                        return ResultBean.factorySuccess(giveRedisListManager().giveValueByKey(key));
                    case HASH:
                        return ResultBean.factorySuccess(giveRedisHashManager().giveValueByKey(key));
                    case SET:
                        return ResultBean.factorySuccess(giveRedisSetManager().giveValueByKey(key));
                    default:
                        return ResultBean.factorySuccess();
                }
            }catch(Exception e){
                log.error("根据Key获取缓存存储的数据处理异常", e);
                return ResultBean.factoryError();
            }
        }
        return ResultBean.factorySuccess();
    }

    /**
     * 属性描述：添加缓存描述
     *
     * @param redisKey     缓存Key名称
     * @param redisMessage 缓存说明
     * @date : 2022/6/22 0022 下午 5:32
     */
    @Override
    @ResponseBody
    public ResultBean saveOrUpdateCacheDescribe(@RequestParam String redisKey, @RequestParam String redisMessage) {
        try {
            giveSpringBean(ICacheDescriptionManager.class).saveOrUpdateCacheDescribe(redisKey, redisMessage);
            return ResultBean.factorySuccess();
        } catch (Exception e) {
            log.error("添加缓存描述处理失败，redisKey：{}；redisMessage：{}", redisKey, redisMessage, e);
            return ResultBean.factoryError();
        }
    }

    /**
     * 属性描述：删除缓存描述
     *
     * @param redisKey 缓存Key名称
     * @date : 2022/6/22 0022 下午 5:32
     */
    @Override
    @ResponseBody
    public ResultBean removeCacheDescribe(@RequestParam String redisKey) {
        try {
            giveSpringBean(ICacheDescriptionManager.class).removeCacheDescribe(redisKey);
            return ResultBean.factorySuccess();
        } catch (Exception e) {
            log.error("删除缓存描述，redisKey：{}；", redisKey, e);
            return ResultBean.factoryError();
        }
    }
}
